package com.se.web;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.se.data.CapturedRequest;
import com.se.data.CapturedRequestService;
import com.se.data.CapturedRequestServiceDatastoreImpl;

@SuppressWarnings("serial")
public class RecentRequestsServlet extends HttpServlet {

	private static final String URL_ENCODING = "UTF-8";
	
	private CapturedRequestService capturedRequestService = new CapturedRequestServiceDatastoreImpl();
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String tag = request.getParameter("tag");
		String breadcrumbFormat = getBreadcrumbFormat(tag);
		List<CapturedRequest> capturedRequests = getCapturedRequests(tag);
		forwardRequest(request, response, breadcrumbFormat, capturedRequests);
	}

	private List<CapturedRequest> getCapturedRequests(String tag) {
		if ((tag == null) || (tag.length() == 0)) {
			return capturedRequestService.getMostRecent();			
		}
		return capturedRequestService.getMostRecentByTag(tag);
	}
	
	private String getBreadcrumbFormat(String tag) {
		try {
			if ((tag == null) || (tag.length() == 0)) {
				return URLEncoder.encode("h,l", URL_ENCODING);	
			}
			return URLEncoder.encode("h,l:" + tag, URL_ENCODING);
		}
		catch (UnsupportedEncodingException e) {
			// nothing we can do here - just return null
		}
		return null;
	}
	
	private void forwardRequest(HttpServletRequest request, HttpServletResponse response,
			String breadcrumbFormat, List<CapturedRequest> capturedRequests)
			throws ServletException, IOException {
		request.setAttribute("breadcrumbFormat", breadcrumbFormat);
		request.setAttribute("requests", capturedRequests);
		RequestDispatcher dispatcher = request.getRequestDispatcher("recent-requests.jsp");
		dispatcher.forward(request, response);
	}
}
